package com.ljkj.cordial.chat.bean;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.Layout;
import android.text.Selection;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.Base64;
import android.util.SparseArray;
import android.util.TypedValue;
import android.widget.EditText;
import android.widget.TextView;

import com.ljkj.cordial.chat.base.ChatApp;
import com.ljkj.cordial.chat.util.LruCacheUtil;
import com.ljkj.cordial.chat.util.ObserverThread;
import com.ljkj.cordial.chat.widget.CenterAlignImageSpan;
import com.nic.view.util.JLog;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * 表情
 */
public class EmojiPackage {
    private final static String regex = "^emoji+[0-4]+[0-9]$|^emoji5+[0-5]$";

    /**
     * 通过文件名获取表情tag
     *
     * @param fileName
     * @return
     */
    public static String getEmojiPositionTagByFileName(String fileName) {
        int start = fileName.indexOf("_") + 1;
        int end = fileName.indexOf(".");
        return fileName.substring(start, end);
    }

    /**
     * 通过tag获取表情文件名
     *
     * @param tag
     * @return
     */
    public static String getAbsoluteFileNameByEmojiPositionTag(String tag) {

        return "file:///android_asset/emoj" + File.separator + "icon_" + tag + ".png";
    }

    public static String getAbsoluteFilePathByFileName(String fileName) {

        return "file:///android_asset/emoj" + File.separator + fileName;
    }

    /**
     * 通过tag获取表情文件名
     *
     * @param tag
     * @return
     */
    public static String getFileNameByEmojiPositionTag(String tag) {

        return "icon_" + tag + ".png";
    }

    /**
     * @param context 获取表情地址数组
     * @return
     */
    public static String[] getFileNames(Context context) {
        try {
            return context.getAssets().list("emoj");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new String[]{};
    }

    /**
     * @param context 获取表情tags地址数组
     * @return
     */
    public static String[] getEmojTags(Context context) {
        try {
            String[] files = context.getAssets().list("emoj");
            String[] strs = new String[files.length];
            for (int i = 0; i < files.length; i++) {
                strs[i] = getEmojiPositionTagByFileName(files[i]);
            }
            return strs;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new String[]{};
    }

    /**
     * 通过名称获取bitmap
     *
     * @param context
     * @param fileName
     * @return
     */
    public static Bitmap getBitmapFromAssets(Context context, String fileName) {
      return   LruCacheUtil.getInstance().getBitmap(fileName);

    }
    public static Bitmap getBitmapFromAssetsCache(Context context, String fileName) {
        Bitmap bitmap = null;
        int dp11 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 48, context.getResources().getDisplayMetrics());
        try {
            String filePath = "emoj" + File.separator + fileName;
            InputStream is = context.getAssets().open(filePath);
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
            bitmap.recycle();
        }
        return resizeImage(bitmap, dp11, dp11);

    }
    public static void initEmojis(Context context) {
        String[] str = getFileNames(context);
        for (String s : str) {
            ObserverThread.create().onBackGroudThread(new Runnable() {
                @Override
                public void run() {
                    LruCacheUtil.getInstance().putBitmap(s, getBitmapFromAssetsCache(context, s));
                }
            });

        }

    }

    public static SpannableString insertEmoj(Context context, String tag) {
        String fileName = getFileNameByEmojiPositionTag(tag);
        Bitmap bmp = getBitmapFromAssets(context, fileName);
        SpannableString string = new SpannableString(tag);
        string.setSpan(new CenterAlignImageSpan(bmp), 0, string.length(), ImageSpan.ALIGN_BASELINE);
        return string;
    }

    public static void insertEmoj(Context context, EditText editText, String tag) {
        ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<SpannableString>() {
            @Override
            public void onAction(SpannableString span) {
                editText.getText().insert(editText.getSelectionStart(), span);
                Selection.removeSelection(span);
            }

            @Override
            public SpannableString onThreadAction() {
                return insertEmoj(context, tag);
            }
        });
    }

    public static String insertEmojText(Context context, EditText editText, String text) {
        return editText.getText().insert(editText.getSelectionStart(), text).toString();
    }

    public static String insertEmojTag(Context context, EditText editText, String emojTag) {
        int start = editText.getSelectionStart();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.insert(start, emojTag);
        return stringBuffer.toString();
    }

    public static SparseArray<String> encodeEmoj(Context context, String text) {
        if (TextUtils.isEmpty(text)) {
            return null;
        }
        String text1 = text;
        SparseArray<String> array = new SparseArray<>();
        for (int i = 0; i < getEmojTags(context).length; i++) {
            String emojTag = getEmojTags(context)[i];
            if (text1.contains(emojTag)) {
                int start = text1.indexOf(emojTag);
                array.put(start, emojTag);
                for (int i1 = start; i1 < text1.length(); i1++) {
                    int p = text1.indexOf(emojTag, i1);
                    if (p != 0) {
                        array.put(p, emojTag);
                    }
                }
            }
        }
        if (array.size() == 0) {
            return null;
        }

        return array;
    }

    /**
     * 是否存在表情
     *
     * @param text
     * @return
     */
    public static boolean isRegex(String text) {
        for (int i = 1; i <= 55; i++) {
            String reg = String.format(".*emoji%s.*", i < 10 ? "0" + i : i + "");
            boolean isB = text.matches(reg);
            if (isB) {
                return true;
            }
        }
        return false;
    }

    public static SpannableStringBuilder decodeEmoji(Context context, String text) {
        SpannableStringBuilder string = new SpannableStringBuilder(text);
        if (!isRegex(text)) {
            return string;
        }
        for (int i = 1; i <= 55; i++) {
            String regex = String.format(".*emoji%s.*", i < 10 ? "0" + i : i + "");
            boolean isB = text.matches(regex);
            if (isB) {
                String tag = regex.replace(".*", "");
                String fileName = getFileNameByEmojiPositionTag(tag);
                Bitmap bmp = getBitmapFromAssets(context, fileName);
                int start = text.indexOf(tag);
                int end = text.lastIndexOf(tag);
                for (int k = start; k <= end; k++) {

                }
                string.setSpan(new CenterAlignImageSpan(bmp), start, start + tag.length(), ImageSpan.ALIGN_BASELINE);
            }
        }
        return string;
    }

    public static SpannableStringBuilder decodeEmoji(Context context, SparseArray<String> strings, String text) {
        SpannableStringBuilder string = new SpannableStringBuilder(text);
        if (strings == null || strings.size() == 0) {
            return string;
        }
        for (int i = 0; i < strings.size(); i++) {
            int start = strings.keyAt(i);
            if (start < 0) {
                continue;
            }
            String tag = strings.get(start);
            String fileName = getFileNameByEmojiPositionTag(tag);
            Bitmap bmp = getBitmapFromAssets(context, fileName);
            //居中对齐imageSpan
            string.setSpan(new CenterAlignImageSpan(bmp), start, start + tag.length(), ImageSpan.ALIGN_BASELINE);
        }
        return string;
    }

    //使用Bitmap加Matrix来缩放
    public static Bitmap resizeImage(Bitmap bitmap, int w, int h) {
        Bitmap BitmapOrg = bitmap;
        int width = BitmapOrg.getWidth();
        int height = BitmapOrg.getHeight();
        int newWidth = w;
        int newHeight = h;

        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // if you want to rotate the Bitmap
        // matrix.postRotate(45);
        Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
                height, matrix, true);
        return resizedBitmap;
    }

    public static String decodeEmoj(Context context, String[] strings) {

        if (strings == null) {
            return null;
        }
        String s1 = strings[0];
        String s2 = strings[1];
        SpannableStringBuilder string = new SpannableStringBuilder(s1);
        for (String s : s2.split(" ")) {
            s1.replaceFirst("&", s);
        }
        return s1;
    }

    /**
     * 查找文本中表情元素并进行转换
     *
     * @param context
     * @param text
     * @return
     */
    public static SpannableStringBuilder getEmojSpannable(Context context, String text) {
        if (TextUtils.isEmpty(text)) {
            text = "";
        }
        SpannableStringBuilder string = new SpannableStringBuilder(text);
        for (String emojTag : getEmojTags(context)) {
            if (text.contains(emojTag)) {
                int start = text.indexOf(emojTag);
                int end = start + emojTag.length();
                String fileName = getFileNameByEmojiPositionTag(emojTag);
                Bitmap bmp = getBitmapFromAssets(context, fileName);
//                string.replace(start, end, "&");
                string.setSpan(new CenterAlignImageSpan(bmp), start, end, ImageSpan.ALIGN_BASELINE);

            }
        }
        return string;
    }

    public static SpannableStringBuilder setRowSize(SpannableString s, int rowSize) {
        int length = s.length();
        SpannableStringBuilder buf = new SpannableStringBuilder();
        int nSize = 0;
        for (int len = 0; len < length; ) {
            String singleStr;
            if (len + rowSize >= length) {
                buf.append(s, len, length);
//                singleStr = s.substring(len, length);
            } else {
//                singleStr = s.substring(len, len + rowSize);
                buf.append(s, len, len + rowSize);
            }
//            buf.append(singleStr);
            if ((buf.length() - nSize) % rowSize == 0) {
                buf.append("\n");
                nSize++;
            }
            len += rowSize;
        }
//        System.out.print(buf.toString());

        return buf;
    }


    public static int getWidth(String text) {

        Paint pFont = new Paint();
        Rect rect = new Rect();
        pFont.getTextBounds(text, 0, text.length(), rect);
        return rect.width();
    }

    public static void getline(TextView textView) {
        Layout layout = textView.getLayout();
        int line = textView.getLayout().getLineCount();
        String result = "";
        String text = layout.getText().toString();
        for (int i = 0; i < line - 1; i++) {
            int start = layout.getLineStart(i);
            int end = layout.getLineEnd(i);


            result += text.substring(start, end) + "\\n";
        }
        int start = layout.getLineStart(line - 1);
        int end = layout.getLineEnd(line - 1);
        result += text.substring(start, end);

    }

    public static String setRowSize(String s, int rowSize) {
        int length = s.length();
        StringBuffer buf = new StringBuffer();
        int nSize = 0;
        for (int len = 0; len < length; ) {
            String singleStr;
            if (len + rowSize >= length) {
                singleStr = s.substring(len, length);
            } else {
                singleStr = s.substring(len, len + rowSize);
            }
            buf.append(singleStr);
            if ((buf.length() - nSize) % rowSize == 0) {
                buf.append("\n");
                nSize++;
            }
            len += rowSize;
        }
//        System.out.print(buf.toString());
        return buf.toString();
    }

    public static void handlerTextThread(Activity activity, String msg, OnHandlerThreadListener listener) {
        if (TextUtils.isEmpty(msg)) {
            return;
        }
//        if (!msg.matches(regex)) {
//            listener.deCodeMsg(msg);
//            return;
//        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                SparseArray<String> array = EmojiPackage.encodeEmoj(ChatApp.getInstance(), msg);
                if (array == null) {
                    String text = setRowSize(msg, 12);
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            listener.deCodeMsg(text);
                        }
                    });

                } else {
                    SpannableStringBuilder text = EmojiPackage.decodeEmoji(ChatApp.getInstance(), array, msg);
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            listener.deCodeMsg(text);
                        }
                    });

                }
            }
        }).start();
    }

    public static void handlerEmojiText(String msg, OnSpannableListener listener) {
        if (TextUtils.isEmpty(msg)) {
            return;
        }
        SparseArray<String> array = EmojiPackage.encodeEmoj(ChatApp.getInstance(), msg);
        if (array == null) {
//            String text = setRowSize(msg, 21);
            SpannableStringBuilder span = new SpannableStringBuilder(msg);
            listener.deCode(span);
        } else {
            SpannableStringBuilder text = EmojiPackage.decodeEmoji(ChatApp.getInstance(), array, msg);
            listener.deCode(text);

        }
    }

    public String encodeImage(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        //读取图片到ByteArrayOutputStream
        bitmap.compress(Bitmap.CompressFormat.PNG, 40, baos); //参数如果为100那么就不压缩
        byte[] bytes = baos.toByteArray();
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }

    public Bitmap decodeImage(String bmMsg) {
        byte[] input = Base64.decode(bmMsg, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(input, 0, input.length);
    }

    public interface OnHandlerThreadListener {


        void deCodeMsg(CharSequence text);
    }

    public interface OnSpannableListener {
        void deCode(SpannableStringBuilder text);
    }

}
